package org.liufeng.course.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.liufeng.course.message.resp.Article;
import org.liufeng.course.message.resp.NewsMessage;
import org.liufeng.course.message.resp.TextMessage;
import org.liufeng.course.util.MessageUtil;




/**
 * 核心服务类
 * 
 * @author liufeng
 * @date 2013-05-20
 */
public class CoreService {
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			
			String accountId = request.getParameter("accountId");
			
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			//消息内容
			String content = requestMap.get("Content");
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);
			
			NewsMessage newMess = new NewsMessage();  
			newMess.setToUserName(fromUserName);  
			newMess.setFromUserName(toUserName);  
			newMess.setCreateTime(new Date().getTime());  
			newMess.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
			newMess.setFuncFlag(0);  

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				//事件类型				
				respContent = "已收到您的信息。我们将尽快进行处理！";
				if(content.indexOf("水库")!=-1){
					respContent = SerchService.returnObj("reser", content.replaceAll("水库", "").trim());
				}else if(content.indexOf("海塘")!=-1){
					respContent = SerchService.returnObj("pond", content.replaceAll("海塘", "").trim());
				}else if(content.indexOf("水闸")!=-1){
					respContent = SerchService.returnObj("gate", content.replaceAll("水闸", "").trim());					
				}else if(content.indexOf("山塘")!=-1){
					respContent = SerchService.returnObj("reser", content.replaceAll("山塘", "").trim());
				}else if(content.indexOf("闸")!=-1){
					respContent = SerchService.returnObj("gate", content.replaceAll("", "").trim());					
				}else if(content.indexOf("塘")!=-1){
					respContent = SerchService.returnObj("pond", content.replaceAll("", "").trim());
				}else if(content.indexOf("help")!=-1){
					respContent = ResofTextMessage.HelpMessager();
				}else if(content.equals("5")){
					//天气预报
					respContent = RequestService.getWeather("B1");
				}else if(content.equals("6")){
					//短期天气
				    respContent = RequestService.getDSYB();
				}else if(content.equals("7")){
					//天气预警
				Map<?, ?> map=RequestService.getYJ2();
				String title = (String) map.get("title");
				String cont = emoji(0x2755)+(String) map.get("cont");
				//普通文本消息
				respContent = title + "\n" + cont;
				}else if(content.equals("8")){
					//卫星云图
					respContent = RequestService.getDSYB();
				}else if(content.equals("9")){
					//台风动态
					respContent = RequestService.getTF();
				}else{
					SendMail.sendEmail("niuxiaofeiyyn@qq.com",toUserName+"--微信平台留言转发~",content);//收件人
					//SendMail.sendEmail("niuxiao@founder.com",toUserName+"--微信平台留言转发~",content);//收件人
				}
				textMessage.setContent(respContent);
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！已收到您的信息。我们将尽快进行处理！";
				textMessage.setContent(respContent);
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！已收到您的信息。我们将尽快进行处理！";
				textMessage.setContent(respContent);
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！已收到您的信息。我们将尽快进行处理！";
				textMessage.setContent(respContent);
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！已收到您的信息。我们将尽快进行处理！";
				textMessage.setContent(respContent);
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					
					//判断公众号
					if ("slj".equals(accountId)){
						Article article1 = new Article();  
						article1.setTitle("感谢您关注奉化市水利局微信服务平台");  
		                article1.setDescription("感谢您关注奉化市水利局官方微信服务平台！");  
		                article1.setPicUrl("http://fhsljchslz.duapp.com/fhsljwx/pic/welcome.jpg");  
		                article1.setUrl("http://www.fhslj.com/");  
		                List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);						
					} else if ("chslz".equals(accountId)){
						Article article1 = new Article();  
						article1.setTitle("感谢您关注奉化市水利局莼湖水利站微信服务平台");  
		                article1.setDescription("感谢您关注奉化市水利局莼湖水利站官方微信服务平台！");  
		                article1.setPicUrl("http://fhsljchslz.duapp.com/fhsljwx/pic/welcome.jpg");  
		                article1.setUrl("http://www.fhslj.com/");  
		                List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);						
					}		
			
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");

					if (eventKey.equals("11")) {
						respContent = "水库查询";
					} else if (eventKey.equals("12")) {
						respContent = "水闸查询";
					} else if (eventKey.equals("13")) {
						respContent = "海塘查询";
					} else if (eventKey.equals("14")) {
						//河道水位潮位查询
						respContent = "点击本信息查看河道水位、潮位信息，由于信息均为实时获取，故会有一点延迟，请谅解！";
						Article article1 = new Article();  
						article1.setTitle("河道水位、潮位信息");  
		                article1.setDescription(respContent);  
		                article1.setPicUrl("http://fhsljchslz.duapp.com/fhsljwx/pic/fhxj.jpg");  
		                article1.setUrl("http://fhsljchslz.duapp.com/fhsljwx/waterLevel1.jsp");
		                List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1);
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);
						
					} else if (eventKey.equals("15")) {
					
					    
					  //河道水位
						respContent = emoji(0x1F514)+"提醒：点击后阅读水利站点雨量统计，由于信息均为实时获取，故会有一点延迟，请谅解！。\n"+"\ue331 截止"+RequestService.getJS(5)+"\n数据来源：奉化市气象站";
						Article article1 = new Article();  
						article1.setTitle("雨情信息");  
		                article1.setDescription(respContent);  
		                article1.setPicUrl("http://fhsljchslz.duapp.com/fhsljwx/pic/rain.jpg");  
		                article1.setUrl("http://fhsljchslz.duapp.com/fhsljwx/rainFall1.jsp");
		                List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1);
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);
				
						
					} else if (eventKey.equals("21")) {
						//天气预报
						respContent = RequestService.getWeather("B1")+"\n"+RequestService.getDSYB();
						Article article1 = new Article();  
						article1.setTitle("天气预报");  
		                article1.setDescription(respContent);  
		                article1.setPicUrl("http://img.9191.cn/tour/201006/08/2010060815275501211.jpg");  
		                article1.setUrl("http://mobile.weather.com.cn/city/101210405.html");
		                List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);
					    
						
						
					} else if (eventKey.equals("22")) {
						//String backCont = RequestService.getYJ();
						Map<?, ?> map=RequestService.getYJ2();
						String title = (String) map.get("title");
						String cont = emoji(0x2755)+(String) map.get("cont");
						//普通文本消息
						respContent = title + "\n" + cont;
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						
				/*		//图文消息  天气预警
						Article article1 = new Article();  
						article1.setTitle(title);  
		                article1.setDescription(cont);  
		                //article1.setPicUrl("http://localhost/Weixin/pic/warn.jpg");  
		                article1.setUrl("http://www.qx121.com/web/tqjb.asp"); 
		                
					    List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);//
					    */
					  
					} else if (eventKey.equals("24")) {
						//图文消息  台风动态
						String backCont = RequestService.getTF();
						Article article1 = new Article();  
						article1.setTitle("台风动态");  
		                article1.setDescription(backCont);  
		                article1.setPicUrl("http://fhsljchslz.duapp.com/fhsljwx/pic/tf.jpg");  
		                article1.setUrl("http://zt.zjmb.gov.cn/tfzt/db/CurTfInfoWap.jsp");  
		              
					    List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					 
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);
					} else if (eventKey.equals("23")) {
						//图文消息  卫星云图
						String YTjtime = (String)RequestService.getYTtime();
						Article article1 = new Article();  
						article1.setTitle(YTjtime+"3D卫星云图");  
		                article1.setDescription("");  
		                article1.setPicUrl("http://agora.ex.nii.ac.jp/digital-typhoon/latest/globe/512x512/ir.jpg");  
		                article1.setUrl("http://fhsljchslz.duapp.com/fhsljwx/2/wxyt.jsp");  
		                //String backCont = RequestService.getTF();
		                Article article2 = new Article();  
		                article2.setTitle("红外线云图");  
		                article2.setDescription("");
		                article2.setPicUrl("http://www.cwb.gov.tw/V7/observe/satellite/Data/HS1P/HS1P.jpg");
		                article2.setUrl("http://fhsljchslz.duapp.com/fhsljwx/2/wxytred.jsp");
		                
		                Article article3 = new Article();  
		                article3.setTitle("风云2号卫星云图");  
		                article3.setDescription("");
		                article3.setPicUrl("http://www.sinaimg.cn/dy/slidenews/17_img/2012_33/2890_1188080_773050.jpg");
		                article3.setUrl("http://fhsljchslz.duapp.com/fhsljwx/2/wxytfy2.jsp");
		                
		                
					    List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					    articleList.add(article2);
					    articleList.add(article3);
					    
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);
						//respContent = "卫星云图";
					} else if (eventKey.equals("25")) {
						
						
					} else if (eventKey.equals("31")) {
						//图文消息  工作动态
						Article article1 = new Article();  
						article1.setTitle("工作动态");  
		                article1.setDescription("点击进入我们网站查看我们的最新工作动态");  
		                article1.setPicUrl("http://fhsljchslz.duapp.com/fhsljwx/pic/31.jpg");  
		                article1.setUrl("http://www.fhslj.com/news.asp?sid=30");  
		                //String backCont = RequestService.getTF();
		                //Article article2 = new Article();  
		                //article2.setTitle("天气预警");  
		                //article2.setDescription("点击查看浙江省气象局天气预警信息");  
		                //article2.setUrl("http://www.zjmb.gov.cn/weather/wapdb/wapyjxxlist.jsp");    
					    List<Article> articleList = new ArrayList<Article>();
					    articleList.add(article1); 
					    //articleList.add(article2);
						// 设置图文消息个数  
						newMess.setArticleCount(articleList.size());  
					     // 设置图文消息包含的图文集合  
						newMess.setArticles(articleList);  
					     // 将图文消息对象转换成xml字符串  
					    respMessage = MessageUtil.newsMessageToXml(newMess);
						
					    //respContent = "卫星云图";
						
						
					} else if (eventKey.equals("32")) {
						respContent = "防汛科普";
					}else if (eventKey.equals("33")) {
						respContent = "您好，我们提供查询奉化市重点水利工程设施基本信息、实时天气、卫星云图、预警信息等内容。可直接输入水库、山塘、海塘、水闸名称并加上其工程类别可查询相应水利工程基本信息。例如：发送\"银峰水库\"或\"横江闸水闸\"或\"外新塘海塘\"即可回复相应水利工程设施基本信息，其他内容可通过菜单进行。";
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						//respContent = "查询帮助";
					}else if (eventKey.equals("34")) {
						respContent = "如果您对本平台有任何建议或需要进行水利方面咨询，请直接回复，我们将热诚为您服务！";
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						//respContent = "建议咨询";
					}else if (eventKey.equals("35")) {
						respContent = "如果您对我们在群众路线教育实践活动有任何建议或意见，请直接回复。";
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						//respContent = "建议咨询";
				}
			
				}
				}

			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}
	/** 
     * emoji表情转换(hex -> utf-16) 
     *  
     * @param hexEmoji 
     * @return 
     */  
    public static String emoji(int hexEmoji) {  
        return String.valueOf(Character.toChars(hexEmoji));  
    }  
}